package com.derbysoft.dswitch.adapter.ihg.common.log;

import com.derbysoft.dswitch.adapter.ihg.common.domain.ReservationDetail;
import com.derbysoft.dswitch.adapter.ihg.common.domain.ReservationLog;
import com.derbysoft.dswitch.adapter.ihg.common.repository.ReservationLogRepository;
import com.derbysoft.dswitch.adapter.ihg.common.utils.LogUtils;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by: jason
 * Date: 2012-08-31
 */
public class ReservationLogTask implements Runnable {
    private ReservationLogRepository reservationLogRepository;
    private ReservationLog reservationLog;
    private Set<LogDetailPair> logDetailPairs;

    public ReservationLogTask(ReservationLogRepository reservationLogRepository,
                              ReservationLog reservationLog, Set<LogDetailPair> logDetailPairs) {
        this.reservationLogRepository = reservationLogRepository;
        this.reservationLog = reservationLog;
        this.logDetailPairs = logDetailPairs;
    }

    @Override
    public void run() {
        saveLog();
    }

    private void saveLog() {
        List<ReservationDetail> reservationDetails = new ArrayList<ReservationDetail>();
        if (CollectionUtils.isNotEmpty(logDetailPairs)) {
            for (LogDetailPair logDetailPair : logDetailPairs) {
                ReservationDetail reservationDetail = new ReservationDetail();
                reservationDetail.setReservationLog(reservationLog);
                reservationDetail.setDetail(LogUtils.toXML(logDetailPair.getObject()));
                reservationDetail.setDirection(logDetailPair.getDirection());
                reservationDetails.add(reservationDetail);
            }
        }
        reservationLog.setReservationDetails(reservationDetails);
        reservationLogRepository.save(reservationLog);
    }
}
